#include "supplierview.h"
#include "core/suppliermodel.h"
#include "gui/shinylistitem.h"
#include "gui/supplierviewadddialog.h"
#include "gui/suppliervieweditdialog.h"
#include "gui/supplierviewdetailsdialog.h"

void SupplierView::initViewComponents()
{
    BaseView::initViewComponents();

    addButton->setText("Add A Supplier");
    this->hideReportsWidgets();
}

void SupplierView::onDetailsRequested(BaseModel *model)
{
    int result;
    SupplierModel *supplier = (SupplierModel *) model;
    SupplierController *ctrl = (SupplierController *) this->getController();
    SupplierViewDetailsDialog *dialog = new SupplierViewDetailsDialog(this, supplier);

    dialog->setSupplier(supplier);
    result = dialog->exec();

    if (result == QDialog::Accepted) {
        qDebug() << "SupplierView::onDetailsRequested: Editing Supplier with id " << supplier->getID();
        SupplierViewEditDialog *editDialog = new SupplierViewEditDialog(this, supplier);
        editDialog->exec();
        supplier = editDialog->getSupplier();

        ctrl->updateSupplier(supplier);
        ctrl->getAll();

        delete editDialog;
    }
}

void SupplierView::onDataUpdate(QList<BaseModel *> models)
{
    ShinyListItem *listItem;
    SupplierModel *supplier;
    QString mainText, subText;
    int i;

    qDebug() << "SupplierView received update";
    BaseView::onDataUpdate(models);

    this->slist->clear();
    for (i = 0; i < models.length(); i++) {
        supplier = (SupplierModel *) models.at(i);
        listItem = new ShinyListItem;
        listItem->setItemIcon("res/supplier.png");

        mainText = supplier->getName();

        subText = supplier->getCountry();

        listItem->setMainText(mainText);
        listItem->setSubText(subText);

        this->slist->addItem(listItem);
    }
}

void SupplierView::onAddButtonClicked() {
    SupplierModel *supplier = new SupplierModel;
    SupplierController *ctrl = (SupplierController *) this->getController();
    SupplierViewAddDialog *dialog = new SupplierViewAddDialog(this);

    dialog->exec();
    supplier = dialog->getSupplier();

    if (supplier) {
        ctrl->addSupplier(supplier);
        ctrl->getAll();
    }

    delete dialog;
}

void SupplierView::initViewSignalsAndSlots() {
    BaseView::initViewSignalsAndSlots();

    connect(this->addButton, SIGNAL(clicked()), this, SLOT(onAddButtonClicked()));
    connect(this, SIGNAL(detailsRequested(BaseModel*)), this, SLOT(onDetailsRequested(BaseModel*)));
}

SupplierView::SupplierView(QWidget *parent):
    BaseView(parent)
{
    this->initViewComponents();
    this->initViewSignalsAndSlots();
}
